//路由守卫

import router from "@/router"
import { getToken } from '@/utils/auth'
import userApi from "@/api/userApi" //验证token ajax


router.beforeEach(async (to, from, next) => {
    /*
            to:即将要进入的路由，路由对象
            from:准备离开的路由，路由对象
            next：是否能进入下一个钩子
        */

    // console.log(to, 666)
    // console.log(from, 888)
    // next()
    // if (to.path == '/login') {
    if (to.meta.permission == false) {
        next() //登陆不需要拦截
    } else {
        //需要拦截
        let token = getToken()
        if (token) {
            //有token:发送token给后端校验
            try {
                let p = await userApi.checkToken(token)
                if (p.data.flag) {
                    //校验通过
                    next()
                } else {
                    next('/login')
                }
            } catch (err) {
                next('/login')
            }
        } else {
            //没有token 跳回登录页
            next('/login')
        }
    }
})